<template>
  <!-- 添加文章 -->
  <div class="essayAdd">
    <div
      class="add"
      style="align-items: center; font-weight: bold; text-align: center"
    >
      <h1>文章添加</h1>
    </div>
    <div class="input" style="margin-top: 10px">
      <el-form
        ref="ruleFormRef"
        style="max-width: 100%"
        :model="form"
        :rules="rules"
         label-width="100px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="文章作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-input v-model="form.type" />
        </el-form-item>
        <el-form-item label="文章状态" prop="state">
          <el-input v-model="form.state" />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <el-input
            v-model="form.content"
            :rows="16"
            type="textarea"
            placeholder="请输入文章内容"
          />
        </el-form-item>
        <el-form-item label="文章封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl + '/oss/upload-img'"
            :data="{ cateDir: 'teacher' }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="addMessage">
        <el-button size="large" type="primary" :plain="true"@click="submitForm(ruleFormRef)"
          >添加文章</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, toRefs, ref } from "vue";
import { useRoute,useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from "element-plus";
import imgUrl from "../../assets/img/6.jpg";
import axios from "@/assets/js/axios";

const route =useRoute();
const router =useRouter();
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const uploadUrl = import.meta.env.VITE_URL;
interface RuleForm {
  id?:number;
  title: String;
  author: String;
  type:String;
  state:number;
  cover: String;
  content: String;
}
const form = reactive<RuleForm>({
  title: "",
  author: "",
  type:"",
  state:0,
  cover: "",
  content: "",
});
const imageUrl = ref("");
const rules = reactive<FormRules<RuleForm>>({
  title: [
    { required: true, message: "请输入文章标题", trigger: "blur" },
    { min: 2, max: 20, message: "用户名2-20个字符长度", trigger: "blur" },
  ],
  author: [{ required: true, message: "请输入文章作者", trigger: "blur" }],
  type: [{ required: true, message: "请输入文章类型", trigger: "blur" }],
  state: [{ required: true, message: "请输入文章类型", trigger: "blur" }],
  cover:[{ required: true, message: "请输入文章封面", trigger: "blur" }],
  content: [{ required: true, message: "请输入文章内容", trigger: "change" }],
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  console.log("response:", response);
  imageUrl.value = response.data.url;
  form.cover = response.data.url;
};
if (route.query.id) {
  //修改元信息标题
  console.log("id:", route.query.id);
  route.meta.title = "讲师管理 / 讲师编辑";
   // 发送请求显示编辑的信息
   axios
    .get("/serviceedu/edu-essay/getById/" + route.query.id, {})
    .then((res: any) => {
      console.log(res);
      form.id = res.data.data.id;
      form.title = res.data.data.title;
      form.author = res.data.data.author;
      form.type = res.data.data.type;
      form.state = res.data.data.state;
      imageUrl.value = res.data.data.cover;
      form.cover = res.data.data.cover;
      form.content = res.data.data.content;
    });
}
//点击保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!",form);

      if (route.query.id) {
        // 进行保存修改
        axios
          .put("/serviceedu/edu-essay/updateEssay", form)
          .then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: "修改文章成功",
              });
              // 跳转列表页
              router.push("/essayList");
            }
          });
      } else {
        // 进行保存新增
        // 发送axios请求保存用户数据
        axios
          .post("/serviceedu/edu-essay/addEssay", form)
          .then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: "保存文章成功",
              });
              // 跳转列表页
              router.push("/essayList");
            }
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//点击重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="less" scoped>
.addMessage {
  margin-left: 5%;
}
:deep .avatar-uploader {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed #cccccc;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: #409eff;
    }
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

</style>
